package com.fg.cloud.factory.controller.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.OrderStatus;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.order.OrderDeliveryDetailEntity;
import com.fg.cloud.manager.entry.order.OrderDeliveryInfoEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.entry.order.vo.OrderDeliveryInfoVo;
import com.fg.cloud.manager.entry.order.vo.ResultDeliveryVo;
import com.fg.cloud.manager.service.order.OrderDeliveryService;

/**
 * Description:发货单
 * @author 陈银龙
 * @date 2017年8月23日上午11:34:44
 */
@Controller
@RequestMapping("orderDelivery")
public class OrderDeliveryController extends BaseController{

	@Autowired
	private OrderDeliveryService orderDeliveryService;
	
	/**
	 * Description:发货单列表(基础查询)
	 * @param request
	 * @param response
	 * @param OrderId
	 * @param OrderFlag
	 * @author 陈银龙
	 * @date 2017年8月23日下午12:40:18
	 */
	@RequestMapping(value = "/orderList", method = RequestMethod.POST)
	@ResponseBody
	public void orderList(HttpServletRequest request, HttpServletResponse response, Integer page, Integer rows, String sort, String order, 
			Integer deliveryStatus, String keyword, Long ageId){
		try {
			if(page == null || page < 0 || rows == null || rows < 0){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<OrderDeliveryInfoEntity> pageinfo = new PageUtils<OrderDeliveryInfoEntity>(page, rows, sort, order);
			Map<String, Object> usmap = pageinfo.getCondition();
			usmap.put("facId",user.getFacId());
			usmap.put("deliveryStatus", deliveryStatus);
			usmap.put("keyword", keyword);
			usmap.put("ageId", ageId);
			orderDeliveryService.orderList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
			
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:发货单详情
	 * @param request
	 * @param response
	 * @param OrderId
	 * @param OrderFlag
	 * @author 陈银龙
	 * @date 2017年8月23日下午12:40:18
	 */
	@RequestMapping(value = "/findDeliveryDatailsById", method = RequestMethod.POST)
	@ResponseBody
	public void findDeliveryDatailsById(HttpServletRequest request, HttpServletResponse response, Long id){
		try {
			if(id == null || id < 0 ){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId",user.getFacId());
			usmap.put("id", id);
			OrderDeliveryInfoEntity oe = orderDeliveryService.findDeliveryDatailsById(usmap);
			doResult(response, true, StatusCode.FINDSUCCESS, oe, ResultType.FIND_SUCCESS);
			
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:根据id查订单详情(厂商订单发货,经销商端退货转发货),用于发货单新增前的显示
	 * @param request
	 * @param response
	 * @param id
	 * @param orderOrigin ,0厂商订单,1经销商退货单,2发货单发货
	 * @author 陈银龙
	 * @date 2017年8月24日上午11:38:45
	 */
	@RequestMapping(value = "/findByIdAndOrderOrigin", method = RequestMethod.POST)
	@ResponseBody
	public void findByIdAndOrderOrigin(HttpServletRequest request, HttpServletResponse response, Long id, Integer orderOrigin){
		try{
			if(id == null || id < 0 || orderOrigin == null){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId", user.getFacId());
			usmap.put("id", id);
			
			// 判断哪来的单子,并查询显示

			if(orderOrigin == 0){//订单
				List<OrderDeliveryDetailEntity> listDetails = orderDeliveryService.findDetailByIdAndOrderOrigin(usmap);
				//OrderInfoEntity oi = orderDeliveryService.findByIdAndOrderOrigin(usmap);
				doResult(response, true, StatusCode.FINDSUCCESS, listDetails, ResultType.FIND_SUCCESS);
			}else if(orderOrigin == 1){// 退货单
				/*OrderReturnEntity oe = orderRefundsService.find(id, user.getFacId(), null);
				doResult(response, true, StatusCode.FINDSUCCESS, oe, ResultType.FIND_SUCCESS);*/
			}else if(orderOrigin == 2){// 发货单
				/*OrderDeliveryInfoEntity oe = orderDeliveryService.findDeliveryDatailsById(usmap);
				doResult(response, true, StatusCode.FINDSUCCESS, oe, ResultType.FIND_SUCCESS);*/
			}else{
				doResult(response, true, StatusCode.FINDERROR, null, "订单来源错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:发货单新增
	 * @param request
	 * @param response
	 * @param dates
	 * @author 陈银龙
	 * @date 2017年8月23日上午11:57:06
	 */
	@RequestMapping(value = "/insertOrder", method = RequestMethod.POST)
	@ResponseBody
	public void insertOrder(HttpServletRequest request, HttpServletResponse response, String dates){
		try {
			OrderDeliveryInfoEntity odi = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(dates), OrderDeliveryInfoEntity.class);
			if(odi.getSourceBillId() ==null || odi.getSourceBillId() < 0 || odi.getDetailList().size() == 0
					|| "".equals(odi.getExpressNo()) || "".equals(odi.getExpressCompany()) || "".equals(odi.getSendDate())){
				doResult(response, false, StatusCode.LACKVALUE, null,ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			odi.setFacId(user.getFacId());
			odi.setCreator(user.getId());
			odi.setUpdater(user.getId());
			odi.setDeliveryStatus(OrderStatus.DELIVERY_SENDALL);
			if(odi.getFacId() == null || odi.getFacId() < 0 ){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			Integer flag = orderDeliveryService.insertOrder(odi);
			if(flag > 0 ){
				doResult(response, true, StatusCode.SAVESUCCESS, flag, ResultType.ADD_SUCCESS);
			}else{
				doResult(response, false, StatusCode.SAVEERROR, flag, "发货数量异常,请检查发货数量");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.ADD_FAULT);
		}
	}
	
	/**
	 * Description:发货单修改
	 * @param request
	 * @param response
	 * @param OrderId  订单Id
	 * @param orderOrigin   订单来源:1退货单,2订货单
	 * @author 陈银龙
	 * @date 2017年8月23日上午11:57:06
	 */
	@RequestMapping(value = "/updateDelOrder", method = RequestMethod.POST)
	@ResponseBody
	public void updateDelOrder(HttpServletRequest request, HttpServletResponse response, String dates){
		try{
			OrderDeliveryInfoEntity odi = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(dates), OrderDeliveryInfoEntity.class);
			if(odi.getId() == null || odi.getId() < 0 || odi.getDetailList().size() == 0){
				doResult(response, false, StatusCode.LACKVALUE, null, "id不能为空或无待发商品");
				return;
			}
			Integer flag = orderDeliveryService.updateDelOrder(odi);
			if(flag > 0 ){
				doResult(response, true, StatusCode.SAVESUCCESS, flag, ResultType.SAVE_SUCCESS);
			}else{
				doResult(response, false, StatusCode.SAVEERROR, flag, ResultType.SAVE_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.SAVE_FAULT);
		}
	}
	
	/**
	 * Description:发货
	 * @param request
	 * @param response
	 * @param id 发货单id
	 * @author 陈银龙
	 * @date 2017年8月25日上午11:50:21
	 */
	@RequestMapping(value = "/deliver", method = RequestMethod.POST)
	@ResponseBody
	public void deliver(HttpServletRequest request, HttpServletResponse response, String dates){
		try{
				OrderDeliveryInfoEntity odi = JSON.parseObject(
						StringEscapeUtils.unescapeHtml4(dates), OrderDeliveryInfoEntity.class);
				if(odi.getId() == null || odi.getId() < 0 || odi.getSendDate() == null
						|| odi.getExpressCompany() == null || odi.getExpressNo() == null ){
					doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
					return;
				}
			// 根据来源查询订单    与发货单中做对比,有则修改无则添加 
			FactoryUserVo user = getCurrentFactoryUser();
			odi.setFacId(user.getFacId());
			ResultDeliveryVo result = orderDeliveryService.deliver(odi);
			if(result.getResultCode() > 0 ){
				doResult(response, true, StatusCode.OPERATIONSUCCESS, result, ResultType.OPERATION_SUCCESS);
			}else{
				doResult(response, false, StatusCode.OPERATIONERROR, result, ResultType.OPERATION_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.OPERATION_FAULT);
		}
	}
	
	/**
	 * 
	 * Description:高级查询
	 * @param oe
	 * @author 陈银龙
	 * @date 2017年8月28日上午9:28:06
	 */
	@RequestMapping(value = "/findBySenior", method = RequestMethod.POST)
	@ResponseBody
	public void findBySenior(HttpServletRequest request, HttpServletResponse response, OrderDeliveryInfoVo ov){
		try{
			if(ov.getRows() == null || ov.getRows() < 0 || ov.getPage() == null || ov.getPage() < 0){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<OrderDeliveryInfoEntity> pageinfo = new PageUtils<OrderDeliveryInfoEntity>(ov.getPage(), ov.getRows(),ov.getSort(),ov.getOrder());
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("beginDate", ov.getBeginDate());
			condition.put("endDate", ov.getEndDate());
			condition.put("productInfo", ov.getProductInfo());
			condition.put("receiveInfo", ov.getReceiveInfo());
			condition.put("ageName", ov.getAgeName());
			condition.put("ageLevelId", ov.getAgeLevelId());
			condition.put("areaId", ov.getAreaId());
			condition.put("areaNumber", ov.getAreaNumber());
			condition.put("facId", user.getFacId());
			condition.put("sourceBillNo", ov.getSourceBillNo());
			condition.put("deliveryNo", ov.getDeliveryNo());
			condition.put("deliveryStatus", ov.getDeliveryStatus());
			condition.put("keyword", ov.getKeyword());

			orderDeliveryService.findBySenior(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * 
	 * Description:发货单删除
	 * @param request
	 * @param response
	 * @param id
	 * @author 陈银龙
	 * @date 2017年8月31日下午4:02:11
	 */
	@RequestMapping(value = "/deleteDelOrder", method = RequestMethod.POST)
	@ResponseBody
	public void deleteDelOrder(HttpServletRequest request, HttpServletResponse response,String ids, Long ageId){
		try{
			if(null == ids || 0 == ids.length()){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			Long[] id = LongUtils.convert(ids.split("[, ]+"));
			Map<String, Object> usmap = new HashMap<String, Object>();
			FactoryUserVo user = getCurrentFactoryUser();
			usmap.put("ids", id);
			usmap.put("facId", user.getFacId());
			usmap.put("ageId", ageId);
			Integer flag = orderDeliveryService.deleteDelOrder(usmap);
			if(flag > 0 ){
				doResult(response, true, StatusCode.REMOVESUCCESS, flag, ResultType.REMOVE_SUCCESS);
			}else{
				doResult(response, false, StatusCode.REMOVEERROR, flag, "删除失败,发货单已签收");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.REMOVE_FAULT);
		}
	}
	
	/**
	 * Description:经销商端查询基础订单头信息
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequestMapping("findOrderInfo")
	@ResponseBody
	public void findOrderInfo(HttpServletRequest request,HttpServletResponse response, Integer page, Integer rows, 
			String sort, String order, OrderInfoEntity entity, String filterText, Long ageId) {
		try {
			if(page == null || page < 0 || rows == null || rows < 0){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<OrderInfoEntity> pageinfo = 
					new PageUtils<OrderInfoEntity>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("ageId", ageId);
			condition.put("facId", user.getFacId());
			condition.put("filterText", filterText);
			//condition.put("ageName", entity.getAgeName());
			condition.put("beginorderStatus", OrderStatus.PENDINGSHIP);//待发货
			condition.put("endorderStatus", OrderStatus.PARTIALSHIP);//部分发货
			
			orderDeliveryService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:流程操作(保存)
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequestMapping("confirmProcess")
	@ResponseBody
	public void confirmProcess(HttpServletRequest request,HttpServletResponse response, Long id){
		try {
			if(id == null || id < 0 ){
				doResult(response, false, StatusCode.LACKVALUE, null, "id不能为空");
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId", user.getFacId());
			usmap.put("id", id);
			usmap.put("status", OrderStatus.DELIVERY_AUDIT);
			
			Long flag = orderDeliveryService.updateProcess(usmap);
			if(flag > 0 ){
				doResult(response, true, StatusCode.OPERATIONSUCCESS, flag, ResultType.OPERATION_SUCCESS);
			}else{
				doResult(response, false, StatusCode.OPERATIONERROR, flag, ResultType.OPERATION_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.OPERATION_FAULT);
		}
	}
	
	/**
	 * Description:流程操作(审核)
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequestMapping("absenceProcess")
	@ResponseBody
	public void absenceProcess(HttpServletRequest request,HttpServletResponse response, Long id){
		try {
			if(id == null || id < 0 ){
				doResult(response, false, StatusCode.LACKVALUE, null, "id不能为空");
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId", user.getFacId());
			usmap.put("id", id);
			usmap.put("status", OrderStatus.DELIVERY_SENDAGO);
			
			Long flag = orderDeliveryService.updateProcess(usmap);
			if(flag > 0 ){
				doResult(response, true, StatusCode.OPERATIONSUCCESS, flag, ResultType.OPERATION_SUCCESS);
			}else{
				doResult(response, false, StatusCode.OPERATIONERROR, flag, ResultType.OPERATION_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.OPERATION_FAULT);
		}
	}
	
	/**
	 * Description:流程操作(收货)
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequestMapping("finishProcess")
	@ResponseBody
	public void finishProcess(HttpServletRequest request,HttpServletResponse response, Long id, Long orderId){
		try {
			if(id == null || id < 0 || orderId == null || orderId <0 ){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			AgencyUserVo user =(AgencyUserVo)UserUtils.getCurrentUser();
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId", user.getFacId());
			usmap.put("id", id);
			usmap.put("status", OrderStatus.DELIVERY_COMPLETE);
			usmap.put("orderId", orderId);
			
			Long flag = orderDeliveryService.updateProcess(usmap);
			
			if(flag > 0 ){
				doResult(response, true, StatusCode.OPERATIONSUCCESS, flag, ResultType.OPERATION_SUCCESS);
			}else{
				doResult(response, false, StatusCode.OPERATIONERROR, flag, ResultType.OPERATION_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.OPERATION_FAULT);
		}
	}
	
	/**
	 * Description:查询一个订单下所有发货单和详情
	 * @param request
	 * @param response
	 * @param Id 订单id
	 * @param OrderFlag
	 * @author 陈银龙
	 * @date 2017年8月23日下午12:40:18
	 */
	@RequestMapping(value = "/findDeliveryByOrderId", method = RequestMethod.POST)
	@ResponseBody
	public void findDeliveryByOrderId(HttpServletRequest request, HttpServletResponse response, Long id, Integer page, Integer rows, 
			String sort, String order){
		try {
			if(id == null || id < 0 || page == null || page < 0 || rows == null || rows < 0){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			AgencyUserVo user =(AgencyUserVo)UserUtils.getCurrentUser();
			PageUtils<OrderDeliveryInfoEntity> pageinfo = new PageUtils<OrderDeliveryInfoEntity>(page, rows,sort,order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("facId",user.getFacId());
			condition.put("id", id);
			orderDeliveryService.findDeliveryByOrderId(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
			
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:查询一个订单下所有发货单和详情(厂商端
	 * @param request
	 * @param response
	 * @param Id 订单id
	 * @param OrderFlag
	 * @author 陈银龙
	 * @date 2017年8月23日下午12:40:18
	 */
	@RequestMapping(value = "/findDeliveryByOrderIdFactory", method = RequestMethod.POST)
	@ResponseBody
	public void findDeliveryByOrderIdFactory(HttpServletRequest request, HttpServletResponse response, Long id, Integer page, Integer rows, 
			String sort, String order){
		try {
			if(id == null || id < 0 || page == null || page < 0 || rows == null || rows < 0){
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
				return;
			}
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<OrderDeliveryInfoEntity> pageinfo = new PageUtils<OrderDeliveryInfoEntity>(page, rows,sort,order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("facId",user.getFacId());
			condition.put("id", id);
			orderDeliveryService.findDeliveryByOrderId(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
			
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
}
